// Package startup
// Created by GoLand
// @User: lenora
// @Date: 2023/12/24
// @Time: 15:17

package startup

import (
	dao2 "camp/microbook/interactive/repository/dao"
	"camp/microbook/internal/repository/dao"
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"go.mongodb.org/mongo-driver/event"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

func InitRedis() redis.Cmdable {
	return redis.NewClient(&redis.Options{
		Addr: "localhost:6378",
	})
}

func InitDb() *gorm.DB {
	db, err := gorm.Open(
		mysql.Open("root:root@tcp(localhost:3306)/camp"),
		&gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		},
	)
	if err != nil {
		panic(err)
	}

	if err := dao.InitTables(db); err != nil {
		panic(err)
	}

	if err := dao2.InitTables(db); err != nil {
		panic(err)
	}

	return db
}

func InitMongoDB() *mongo.Database {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	monitor := &event.CommandMonitor{
		Started: func(ctx context.Context, startedEvent *event.CommandStartedEvent) {
			fmt.Println("start--", startedEvent.Command)
		},
	}
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://root:bmp@localhost:27017").SetMonitor(monitor))
	if err != nil {
		panic(err)
	}
	return client.Database("camp")
}
